package org.itzixi.netty.websocket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 创建心跳助手类
 */
//SimpleChannelInboundHandler:对于请求来说相当于入站
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        // 判断evt是否是IdleStateEvent(用于触发用户事件，包括读空闲/写空闲/读写空闲)
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent)evt;
            if (event.state() == IdleState.READER_IDLE){
//                System.out.println("进入读空闲...");
            } else if (event.state() == IdleState.WRITER_IDLE){
//                System.out.println("进入写空闲...");
            } else if (event.state() == IdleState.ALL_IDLE){
                System.out.println("channel关闭前，client数量 : " + ChatHandler_Single.clients.size());
                //关闭无用的channel，防止资源浪费
                Channel channel = ctx.channel();
                channel.close();
                System.out.println("channel关闭后，client数量 : " + ChatHandler_Single.clients.size());
            }
        }
    }
}
